
import { _decorator, Component, Node, Sprite, UITransform, Animation, animation, AnimationClip, Vec3, SpriteFrame } from 'cc'
import { EntityManager } from '../../Base/EntityManager'
import { ENTITY_TYPE_ENUM, DIRECTION_ENUM, ENTITY_STATE_ENUM, EVENT_ENUM } from '../../Enums'
import { WoodenSkeletonStateMachine } from './WoodenSkeletonStateMachine'
import EventManager from '../../Runtime/EventManager'
import DataManager from '../../Runtime/DataManager'
import { EnemyManager } from '../../Base/EnemyManager'
import { IEntity } from '../../Levels'
const { ccclass, property } = _decorator


@ccclass('WoodenSkeletonManager')
// export class WoodenSkeletonManager extends EntityManager {
export class WoodenSkeletonManager extends EnemyManager {
    async init(params: IEntity) {
        this.fsm = this.addComponent(WoodenSkeletonStateMachine)
        await this.fsm.init()
        super.init(params)

        // 玩家移动结束后，要调整木骷髅的方向以朝向玩家
        // EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection, this)
        // EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection, this)
        EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack, this)
        // EventManager.Instance.on(EVENT_ENUM.ATTACK_ENEMY, this.onDead, this)

        // this.onChangeDirection(true) // 初始化时也需要调整方向
    }

    onDestroy() {
        // EventManager.Instance.off(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection)
        // EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection)
        EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack)
        // EventManager.Instance.off(EVENT_ENUM.ATTACK_ENEMY, this.onDead)
        super.onDestroy()
    }

    // onChangeDirection(isInit: boolean = false) {} // 父类里实现了

    onAttack() {
        if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
            return
        }

        const { x: playerX, y: playerY, state: playerState } = DataManager.Instance.player

        // 如果玩家在木骷髅附近的4个格子里并且状态不是死亡状态就攻击玩家
        if (
            ((this.x === playerX && Math.abs(this.y - playerY) <= 1) ||
                (this.y === playerY && Math.abs(this.x - playerX) <= 1))
            && playerState !== ENTITY_STATE_ENUM.DEATH
            && playerState !== ENTITY_STATE_ENUM.AIR_DEATH
        ) {
            this.state = ENTITY_STATE_ENUM.ATTACK
            EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
        } else {
            this.state = ENTITY_STATE_ENUM.IDLE
        }
    }
}
